<script lang="ts" setup name="MapContainr">
  import { onMounted, onUnmounted, ref } from 'vue';
  import AMapLoader from '@amap/amap-jsapi-loader';
  // import chlorophyllConcentration from '@/assets/map/chlorophyllConcentration.json';
  import { getRasterValue } from '@/api/geoserver';
  import message from '@arco-design/web-vue/es/message';
  import { queryWmsLayer } from '@/api/riversManger/wmsLayerManger';

  const map = ref();

  const currentWmsLayers = ref<any[]>([]);

  const emits = defineEmits(['mapClick']);
  const mapClick = (event: any) => {
    emits('mapClick', event);
  };

  const wmsLayers = ref<any[]>([]);
  const wmsLayerObjects = ref<any>({});
  const layerClick = async (event: any) => {
    console.log('鼠标点击对象：', event);

    const [x, y] = event.pos;
    // 获取当前地图显示的图层
    const currentLayers: any[] = map.value.getLayers();
    currentWmsLayers.value = currentLayers.filter((item) =>
      item.CLASS_NAME?.includes('AMap.TileLayer.WMS')
    );
    try {
      // 从本地geroserver查询数据点信息
      const data = await Promise.all(
        currentWmsLayers.value.map((item: any) => {
          return (async () => {
            const res: any = await getRasterValue(x, y, item.Ml, item.kl);
            let value = 0;
            const features = res.features[0];
            const layer = wmsLayerObjects.value[item.kl.LAYERS];
            // 获取数据不为空切不是背景值
            if (features && features.properties.GRAY_INDEX !== layer.nonData) {
              value = features.properties.GRAY_INDEX;
            }
            return {
              value,
              ...layer,
            };
          })();
        })
      );
      if (data && data.length > 0) mapClick({ data, ...event.lnglat });
    } catch (e) {
      console.log('获取点数据异常', e);
    }
  };

  onMounted(() => {
    message.info('地图加载中...');
    AMapLoader.load({
      // 申请好的Web端开发者Key，首次调用 load 时必填
      key: '2d5d787b9a968fcc23b63b42022cbf66',
      // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
      version: '2.0',
      // 加载 AMapUI
      AMapUI: {
        version: '1.1', // AMapUI 版本
      },
      // 需要使用的的插件列表，如比例尺'AMap.Scale'等
      plugins: ['AMap.Geocoder', 'AMap.GeoJSON'],
      // layers: [layer]
    })
      .then(async (AMap) => {
        const layers = await queryWmsLayer();
        currentWmsLayers.value.forEach((item: any) => {});
        wmsLayers.value = layers.data.map((element) => {
          const data = {
            ...element,
            enable: false,
            layer: new AMap.TileLayer.WMS({
              url: element.url, // wms服务的url地址
              blend: true, // 地图级别切换时，不同级别的图片是否进行混合
              tileSize: element.tileSize, // 加载WMS图层服务时，图片的分片大小
              params: {
                VERSION: element.version, // wms 版本
                TRANSPARENT: element.transparent,
                LAYERS: element.layerName, // 图层名
                FORMAT: element.format,
              },
            }),
          };
          wmsLayerObjects.value[element.layerName as string] = data;
          return data;
        });
        console.log('layers:', layers);

        // 设置地图容器id
        map.value = new AMap.Map('container', {
          // 是否为3D地图模式
          zoom: 14, // 初始化地图级别
          // 初始化地图中心点位置
          center: [119.31573516, 26.36985657],
        });
        AMapUI.loadUI(['control/BasicControl'], (BasicControl: any) => {
          // 图层切换控件
          map.value.addControl(
            new BasicControl.LayerSwitcher({
              baseLayers: [
                {
                  id: 'base',
                  enable: true,
                  name: '标准图',
                  layer: new AMap.TileLayer(),
                },
                {
                  id: 'sate',
                  enable: true,
                  name: '卫星图',
                  layer: new AMap.TileLayer.Satellite(),
                },
              ],
              overlayLayers: wmsLayers.value,
              // right top，右上角
              position: {
                top: '100px',
                right: '21%',
              },
              theme: 'layer-switcher',
            })
          );
        });

        // map.value.add(geoJson);
        map.value.on('complete', () => message.success('地图加载成功'));
        map.value.on('click', layerClick);

        map.value.setFitView();
      })
      .catch((e) => {
        console.error(e);
      });
  });

  onUnmounted(() => {
    map.value?.destroy();
  });
</script>

<template>
  <div class="container">
    <div id="container"></div>
  </div>
</template>

<style scoped>
  .container {
    width: 100%;
    height: 100%;
    background-color: rgb(11, 27, 78);
  }
  #container {
    width: 100%;
    height: 100%;
    background-size: cover;
    mask-image: radial-gradient(circle at center, black 30%, transparent 70%);
  }
  #container::after {
    content: '';
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    background: transparent;
    pointer-events: none;
    mask-image: radial-gradient(circle at center, transparent 30%, black 70%);
    backdrop-filter: blur(
      10px
    ); /* Adjust this value to change the blur effect */
  }
</style>
